<template>
  <el-dialog v-model="dialogVisible" title="保存表情" width="500px" :close-on-click-modal="false">
    <div class="save-options">
      <div class="preview">
        <img :src="previewUrl" alt="预览" />
      </div>

      <el-form :model="form" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="请输入表情名称" />
        </el-form-item>

        <el-form-item label="标签">
          <el-select v-model="form.tag" placeholder="选择标签" class="tag-select">
            <el-option label="全部" value="" />
            <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.name" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useEmojiStore } from '../stores/emoji'

const props = defineProps({
  modelValue: Boolean,
  imageData: Object
})

const emit = defineEmits(['update:modelValue', 'save'])
const emojiStore = useEmojiStore()

const dialogVisible = ref(false)
const previewUrl = ref('')
const tags = ref([])
const form = ref({
  name: '',
  tag: ''  // 默认为空，表示"全部"标签
})

// 监听对话框显示状态
watch(() => props.modelValue, async (val) => {
  dialogVisible.value = val
  if (val && props.imageData) {
    await initializeForm()
  }
})

watch(() => dialogVisible.value, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    form.value = {
      name: '',
      tag: ''
    }
  }
})

// 初始化表单数据
const initializeForm = async () => {
  // 设置预览图
  if (props.imageData.data instanceof Blob) {
    previewUrl.value = URL.createObjectURL(props.imageData.data)
  }

  // 设置默认名称
  form.value.name = props.imageData.name || new Date().getTime().toString()

  // 加载标签列表
  await loadTags()
}

// 加载标签列表
const loadTags = async () => {
  try {
    console.log('加载保存对话框的标签列表')
    tags.value = await emojiStore.getAllTags()
  } catch (error) {
    console.error('加载标签失败:', error)
    ElMessage.error('加载标签失败')
  }
}

// 提交表单
const handleSubmit = () => {
  if (!form.value.name.trim()) {
    ElMessage.warning('请输入表情名称')
    return
  }

  emit('save', {
    name: form.value.name.trim(),
    tag: form.value.tag  // 直接传递选中的标签
  })
}

// 组件卸载时清理预览URL
onUnmounted(() => {
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value)
  }
})
</script>

<style lang="scss" scoped>
.save-options {
  .preview {
    text-align: center;
    margin-bottom: 20px;

    img {
      max-width: 200px;
      max-height: 200px;
      border-radius: 4px;
    }
  }

  .tag-select {
    width: 100%;
  }
}
</style>